package com.xb.loan.admin.web.controller.system;

import com.xb.loan.admin.Constants;
import com.xb.loan.admin.bean.system.OssOperatorRole;
import com.xb.loan.admin.bean.system.OssRole;
import com.xb.loan.admin.service.rolemanager.RoleManagerService;
import com.xb.loan.admin.service.system.OperatorRoleService;
import com.xb.loan.admin.service.system.OssMenuServer;
import com.xb.loan.admin.web.controller.BaseController;
import com.xb.loan.log.exception.BizException;
import com.xb.loan.util.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class RoleManagementController extends BaseController {
	
	private static final Logger logger = LoggerFactory.getLogger(RoleManagementController.class);
	
	private List<Map<String, Object>> dataResult = new ArrayList<Map<String, Object>>();
	
	private final static String TOP_MENUID = "100000000";//一级菜单默认父级编码

	@Autowired
	private OssMenuServer ossMenuServer;
	
	@Autowired
	private RoleManagerService roleManagerService;
	
	@Autowired
	private OperatorRoleService operatorRoleService;
	
	@RequiresPermissions("103010101")
	@RequestMapping(value="/roleManagement/showSaveOrUpdateRole",method=RequestMethod.GET)
    public String showSaveOrUpdateRole(Model model,HttpServletRequest req,
            @RequestParam("type")  String type, 
            @RequestParam(value = "roleId", required = false)  String roleId, 
            @RequestParam(value = "roleName", required = false)  String roleName) throws UnsupportedEncodingException {
		logger.info("RoleManagementController.showAddRole type="+type+",roleId="+roleId+",roleName="+roleName);
		model.addAttribute("type", type);
		model.addAttribute("roleId", roleId);
	
		if (!StringUtils.isEmpty(roleName)) {
		    model.addAttribute("roleName",  java.net.URLDecoder.decode(roleName,"UTF-8"));
        }
		this.getLoginUserType(req, model);
		return "/systemManagement/roleManagement/saveOrUpdateRole/saveOrUpdateRole";
	}
	
	/**
	 * 查询角色列表、权限树
	 * @param type
	 * @param roleId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/roleManagement/queryTree",method=RequestMethod.POST )
	public Map<String, Object> queryTree(
	        @RequestParam("type")  String type, 
	        @RequestParam(value = "roleId", required = false) String roleId,HttpServletRequest req){
		logger.info("RoleManagementController.queryTree type="+type+",roleId="+roleId);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		//List<String> partnerIdList = null;
		List<String> menuIdList = null;
		if ("update".equals(type) && !StringUtils.isEmpty(roleId)) {
			//partnerIdList = roleManagerService.queryPartnerIdListByRoleId(roleId);
			menuIdList = roleManagerService.queryMenuIdListByRoleId(roleId);
		}
		dataResult.clear();
		

		String operatorId = super.getOperatorId(req);
		String loginRoleId="";
        if(!"10000".equals(operatorId)){
	        List<OssOperatorRole> rolelist = operatorRoleService.queryOperatorRoleByOperatorId(operatorId);
	        if(rolelist != null && rolelist.size() > 0){
	        	loginRoleId = rolelist.get(0).getRoleId();
	        }
        }else{
        	loginRoleId = "";
        }		
		
		this.selectOssMenuTree(TOP_MENUID,null,menuIdList,loginRoleId);		
		
		/**
		List<Map<String, Object>> chList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> parentList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> list = ossPartnerInfoService.queryPartnerInfoByLevel(1, "1,2", -1,loginRoleId);
		for (Map<String, Object> map : list) {//查询当前角色所拥有的代销商并做标记
			if (partnerIdList != null) {
				if (partnerIdList.contains(map.get("PARTNER_ID"))) {
					map.put("CHECKED", "checked");
				}
			}
			
			String parentPartnerid = (String) map.get("PARENT_PARTNERID");
			if("0".equals(parentPartnerid)){
				parentList.add(map);
			}else{
				chList.add(map);
			}
		}
		resultMap.put("partnerData", parentList);
		resultMap.put("chData", chList);
		**/
		
		resultMap.put("rightData", dataResult);
		return resultMap;
	}
	
	/**
	 * 添加或修改角色
	 * @param type
	 * @param roleId
	 * @param roleName
	 * @param partnerIds
	 * @param menuIds
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/roleManagement/saveOrUpdateRole",method=RequestMethod.POST )
	public Map<String, Object> saveOrUpdateRole(HttpServletRequest req,
	        @RequestParam("type") String type,
	        @RequestParam(value = "roleId", required = false) String roleId,
	        @RequestParam("roleName") String roleName,
	        @RequestParam("partnerIds") String partnerIds,
	        @RequestParam("menuIds") String menuIds){
		logger.info("RoleManagementController.saveOrUpdateRole type="+type+",roleId="+roleId+",roleName="+roleName+",partnerIds="+partnerIds+",menuIds="+menuIds);
		Map<String, Object> map = new HashMap<String, Object>();
		String msg = OPERATE_RESULT_SUCCESS_MSG;
		String errorCode = OPERATE_RESULT_SUCCESS_CODE;
		String[] partnerIdArray = partnerIds.split(",");
		String[] menuIdArray = menuIds.split(",");
		
		String operatorId = super.getOperatorId(req);
		String loginRoleId="";
        if(!"10000".equals(operatorId)){
	        List<OssOperatorRole> rolelist = operatorRoleService.queryOperatorRoleByOperatorId(operatorId);
	        if(rolelist != null && rolelist.size() > 0){
	        	loginRoleId = rolelist.get(0).getRoleId();
	        }
        }else{
        	loginRoleId = "10000";
        }
				
				
		try {
			roleId = roleManagerService.saveOrUpdateRole(type, roleId, roleName, partnerIdArray, menuIdArray,loginRoleId);
			addOperateLog(req, "t_oss_role", ("save".equals(type)==true?"添加":"修改")+"了角色 roleId="+roleId+",roleName="+roleName, roleId, "save".equals(type)==true? Constants.OPERATE_TYPE_ADD:Constants.OPERATE_TYPE_MODIFY);
		} catch (Exception e) {
			if (e instanceof BizException) {
				msg = ((BizException)e).getMessage();
				errorCode = ((BizException)e).getKey();
			}else {
				msg = OPERATE_RESULT_EXCEPTION_MSG;
				errorCode = OPERATE_RESULT_EXCEPTION_CODE;
			}
			logger.error(msg,e);
		}finally{
			map.put("msg", msg);
			map.put("errorCode", errorCode);
		}
		return map;
	}
	
	/**
	 * 递归菜单树
	 * @param parentMenuId
	 * @param parentData
	 * @param menuIdList
	 */
	private void selectOssMenuTree(String parentMenuId,Map<String, Object> parentData,List<String> menuIdList,String roleId){
		if (parentData!=null && menuIdList!=null && menuIdList.contains(parentData.get("MENU_ID"))) {
			parentData.put("CHECKED", "checked");
		}
		List<Map<String, Object>> list = ossMenuServer.queryOssMenuByParentMenuId(parentMenuId,roleId);
		if (list==null || list.size()==0) {
			return;
		}else {
			if (parentData!=null) {
				parentData.put("SUB_DATA", list);
			}
		}
		if (TOP_MENUID.equals(parentMenuId)) {
			dataResult.addAll(list);
		}
		for (Map<String, Object> map : list) {
			selectOssMenuTree(map.get("MENU_ID").toString(),map,menuIdList,roleId);
		}
	}
	
	@RequiresPermissions("103010200")
	@RequestMapping(value="/roleManagement/showRoleManager",method=RequestMethod.GET )
	public String showRoleManager(Model model,HttpServletRequest req){
		logger.info("RoleManagementController.showRoleManager");
		this.getLoginUserType(req, model);
		return "/systemManagement/roleManagement/roleManager/roleManager";
	}
	
	/**
	 * 分页查询角色列表
	 * @param pageNum
	 * @param numPerPage
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/roleManagement/queryRoleList",method=RequestMethod.POST )
	public Map<String, Object> queryRoleList(@RequestParam("pageNum") int pageNum,@RequestParam("numPerPage") int numPerPage,HttpServletRequest req){
		logger.info("RoleManagementController.queryRoleList pageNum="+pageNum+",numPerPage="+numPerPage);
		Map<String, Object> map = new HashMap<String, Object>();
		
		String operatorId = super.getOperatorId(req);
		String loginRoleId="";
	    List<OssOperatorRole> rolelist = operatorRoleService.queryOperatorRoleByOperatorId(operatorId);
	    if(rolelist != null && rolelist.size() > 0){
	       	loginRoleId = rolelist.get(0).getRoleId();
	    }
		
		
		List<OssRole> list = roleManagerService.queryOssRoleByPage(loginRoleId,numPerPage, pageNum);
		int totalCount = roleManagerService.queryOssRoleCount(loginRoleId);
		map.put("json", list);
		map.put("totalCount", totalCount);
		return map;
	}
	
	/**
     * 删除角色
     * @param roleId
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/roleManagement/delete",method=RequestMethod.POST )
    public Map<String, Object> delete(HttpServletRequest req,@RequestParam(value="roleId")String roleId){
        logger.info("RoleManagementController.delete roleId="+roleId);
        Map<String, Object> map = new HashMap<String, Object>();
        String msg = OPERATE_RESULT_SUCCESS_MSG;
        String errorCode = OPERATE_RESULT_SUCCESS_CODE;
        try {
            int count = roleManagerService.queryOperatorRoleCountByRoleId(roleId);
            if (count>0) {
                msg = "无法删除，该角色已分配给操作员！";
                errorCode = "2";
            }else {
                roleManagerService.deleteByRoleId(roleId);
                addOperateLog(req, "t_oss_role", "删除了角色 roleId="+roleId, roleId, Constants.OPERATE_TYPE_DELETE);
            }
        } catch (Exception e) {
            if (e instanceof BizException) {
				msg = ((BizException)e).getMessage();
				errorCode = ((BizException)e).getKey();
			}else {
				msg = OPERATE_RESULT_EXCEPTION_MSG;
				errorCode = OPERATE_RESULT_EXCEPTION_CODE;
			}
            logger.error(msg,e);
        }finally{
            map.put("msg", msg);
            map.put("errorCode", errorCode);
        }
        return map;
    }
}
